package com.caishi.lkx.user.api;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caishi.lkx.common.BaseApi;
import com.caishi.lkx.common.role.Role;
import com.caishi.lkx.common.role.Roles;
import com.caishi.lkx.user.ienum.type.UserAccountType;
import com.caishi.lkx.user.ienum.type.UserType;
import com.caishi.lkx.user.model.*;
import com.caishi.lkx.user.service.*;
import com.caishi.lkx.user.vo.AdminUserListVo;
import com.zzw.common.Wrappers;
import com.zzw.common.exception.BizException;
import com.zzw.common.utils.CommonUtil;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.OptionalInt;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author by keray
 * date:2021/4/19 4:26 下午
 */
@Tag(name = "管理员相关")
@RestController
@RequestMapping("/user/cu/admin/user")
@Roles({Role.admin})
public class AdminUserApi extends BaseApi {
    @Resource
    private IAdminUserService adminUserService;

    @Resource
    private ILoginInfoService loginInfoService;

    @Resource
    private IActionRoleService actionRoleService;

    @Resource
    private IPositionService positionService;

    @Resource
    private IUserService<UserModel> userService;
    @Resource
    private IDistributionLevelsService distributionLevelsService;
    @Resource
    private IDistributionUserService distributionUserService;


    @GetMapping("/page")
    public IPage<?> list(@ModelAttribute AdminUserModel model,
                         @ModelAttribute Page<AdminUserModel> page,
                         @RequestParam(defaultValue = "true") Boolean vo,
                         @RequestParam(defaultValue = "false") Boolean role,
                         @RequestParam(defaultValue = "false") Boolean position,
                         Long positionId,
                         String positionCode
    ) {
        if (StrUtil.isNotBlank(positionCode)) {
            PositionModel m = positionService.selectFirst(Wrappers.<PositionModel>lambdaQuery()
                    .eq(PositionModel::getCode, positionCode)
            );
            positionId = m == null ? -1 : m.getId();
        }
        Map<String, Object> query = clearReturnEmptyStr(model.toMap());
        query.put("positionId", positionId);
        IPage<AdminUserModel> result = adminUserService.search(clearReturnEmptyStr(query), page, page.isSearchCount());
        result.setRecords(result.getRecords().parallelStream().map(v -> {
            v.setMobile(CommonUtil.mobileSafe(v.getMobile()));
            if (role) {
                v.setRoles(actionRoleService.selectUserRoles(v.getId()));
            }
            if (position) {
                v.setPositions(positionService.userHavePosition(v.getId()));
            }
            if (vo) {
                AdminUserListVo data = AdminUserListVo.model2Vo(v);
                data.setRoleNames(role ? v.getRoles().stream().map(ActionRoleModel::getName).collect(Collectors.toList()) : null);
                data.setPositionNames(position ? v.getPositions().stream().map(PositionModel::getName).collect(Collectors.toList()) : null);
                data.setLoginData(loginInfoService.userLastLoginData(v.getId()));
                LoginInfoModel infoModel = loginInfoService.selectUserLoginInfo(data.getId(), UserAccountType.username);
                if (infoModel != null) {
                    data.setAccount(infoModel.getAccount());
                }
                return data;
            }
            return v;
        }).collect(Collectors.toList()));
        return result;
    }

    @PostMapping("/enable/{status}/{id}")
    public void settingEnable(@PathVariable String id, @PathVariable Boolean status) {
        adminUserService.lockUser(status, id);
    }

    @GetMapping("/position-admin/{id}")
    public List<AdminUserModel> positionAdmin(@PathVariable String id, String name, @RequestParam(defaultValue = "10") Integer size) {
        return adminUserService.search(MapUtil.<String, Object>builder()
                .put("name", name)
                .put("positionId", id)
                .build(), new Page<AdminUserModel>().setCurrent(1).setSize(size), false).getRecords();
    }

    @GetMapping("/edit/detail/{id}")
    public AdminUserModel adminEditDetail(@PathVariable String id) {
        AdminUserModel model = adminUserService.getUserDetail(id);
        model.setRoles(actionRoleService.selectUserRoles(model.getId()));
        model.setPositions(positionService.userHavePosition(model.getId()));
        if (StrUtil.isNotBlank(model.getParentId())) {
            AdminUserModel userDetail = adminUserService.getUserDetail(model.getParentId());
            if (null != userDetail) {
                List<PositionModel> positionModels = positionService.userHavePosition(userDetail.getId());
                userDetail.setPositions(positionModels);
            }
            model.setParent(userDetail);
        }
        return model;
    }

    //    区分是自主注册还是推荐注册
    @PostMapping("/edit/add")
    public AdminUserModel adminUserAdd(
            @ModelAttribute AdminUserModel model,
            @RequestParam(required = false) List<String> roleIds,
            @RequestParam(required = false) List<Long> positionIds,
            String username,
            String password,
            String recommendUserId,
            @RequestParam(required = false,defaultValue = "false")
            Boolean isAddDistributer
    ) throws BizException {
        String currentUserId = userContext.currentUserId();
        if(currentUserId==null||currentUserId.isEmpty()){
            if(recommendUserId==null){
                // 自主注册
                model.addUserType(UserType.admin);
                // 自主注册的只能是分销员,cu_action_role的id
                AdminUserModel user = adminUserService.addUser(model, List.of(Role.distributer.name()), positionIds, username, password, UserAccountType.username);
                // 获取分销等级id
                List<DistributionLevelsModel> list = distributionLevelsService.list();

                if (!list.isEmpty()) {
                    DistributionLevelsModel lastLevel = list.get(list.size() - 1);
                    // 使用 lastLevel.getId() 等字段进行后续操作

                    // 随机挂靠在某一代理商下
                    List<DistributionUser> list1 = distributionUserService.list();
                    if(!list1.isEmpty()){
                        Random  random = new Random();
                        int index = random.nextInt(list1.size());

                        DistributionUser user1=DistributionUser.builder()
                                .id(user.getId())
                                .deleted(false)
                                .createdAt(LocalDateTime.now())
                                .parentId(list1.get(index).getId())
                                .levelsId(lastLevel.getId())
                                .build();
                        distributionUserService.save(user1);
                    }
                }

                return user;
            }else{
                // 推荐注册
                model.addUserType(UserType.admin);
                // 自主注册的只能是分销员,cu_action_role的id
                AdminUserModel user = adminUserService.addUser(model,List.of(Role.distributer.name()), positionIds, username, password, UserAccountType.username);
                // 获取推荐人的level_id
                List<DistributionLevelsModel> list = distributionLevelsService.list();
                DistributionUser parent = distributionUserService.getById(recommendUserId);
                Integer levelId = null;
                if(parent.getLevelsId()==null){
                    levelId=list.get(list.size()-1).getId();
                }else{
                    // 末级没有权限再发展下级
                    if(parent.getLevelsId()!=list.get(list.size()-1).getId()){
                        OptionalInt indexOpt= IntStream.range(0, list.size()).filter((e)->{
                            return parent.getLevelsId()==list.get(e).getId();
                        }).findFirst();
                        levelId=list.get(indexOpt.getAsInt()+1).getId();
                    }
                }
                if(levelId!=null){
                    DistributionUser child = DistributionUser.builder()
                            .id(user.getId())
                            .deleted(false)
                            .createdAt(LocalDateTime.now())
                            .parentId(parent.getId())
                            .levelsId(levelId)
                            .build();
                    distributionUserService.save(child);
                }
                // levelsId

                return user;
            }
        }else{
            model.addUserType(UserType.admin);
            AdminUserModel adminUserModel = adminUserService.addUser(model, roleIds, positionIds, username, password, UserAccountType.username);
            if(roleIds.contains(Role.distributer.name())){
                // 如果是加分销员，有额外操作
                List<DistributionLevelsModel> list = distributionLevelsService.list();
                DistributionUser child = DistributionUser.builder()
                        .id(adminUserModel.getId())
                        .deleted(false)
                        .createdAt(LocalDateTime.now())
                        .build();
                List<DistributionUser> list1 = distributionUserService.list();

                // 如果不是在分销页面添加的
                if(!isAddDistributer){
                    child.setLevelsId(list.get(list.size()-1).getId());
                    if(list1.stream().anyMatch(distributionUser -> {
                        return distributionUser.getId().equals(currentUserId);
                    })){
                        child.setParentId(currentUserId);
                    }else{
                        if(!list1.isEmpty()){
                            Random  random = new Random();
                            int index = random.nextInt(list1.size());
                            child.setParentId(list1.get(index).getId());
                            distributionUserService.save(child);
                        }
                    }

                }else{
                    var levelsId=list.get(list.size()-1).getId();
                    boolean  flag=false;
                    for(var i=0;i<list1.size();i++){
                        if(list1.get(i).getId().equals(recommendUserId)){
                            flag=true;
                            if(list1.get(i).getLevelsId()==null){
                                levelsId=list.get(0).getId();
                            }else{
                                for(var j=0;j<list.size();j++){
                                    if(list.get(j).getId()==list1.get(i).getLevelsId()){
                                        levelsId=list.get(j+1).getId();
                                        break;
                                    }
                                }
                                break;
                            }

                        }
                    }
                    if(flag){
                        child.setParentId(recommendUserId);
                        child.setLevelsId(levelsId);
                        distributionUserService.save(child);
                    }else{
                        // 传入的推荐人id不合法
                        throw new BizException("用户id不存在");
                    }
                }
            }

            return adminUserModel;
        }

    }

    @PutMapping("/edit/update")
    @Transactional(rollbackFor = Exception.class)
    public AdminUserModel adminUserAdd(
            @ModelAttribute AdminUserModel model,
            @RequestParam(required = false) List<String> roleIds,
            @RequestParam(required = false) List<Long> positionIds
    ) {
        model.setMobile(null);
        model.setApiRoleName(String.join(",", roleIds));
        adminUserService.update(model);
        actionRoleService.userSettingRolesByIds(model.getId(), roleIds);
        positionService.userSettingPositionByIds(model.getId(), positionIds);
        return model;
    }

    @Operation(summary = "机构管理员信息修改")
    @PutMapping("/edit/group-update")
    @Transactional(rollbackFor = Exception.class)
    public AdminUserModel adminUserAdd(@ModelAttribute AdminUserModel model) {
        adminUserService.update(model);
        return model;
    }

    @DeleteMapping("/delete")
    @Transactional
    public Boolean delete(@RequestParam String id) {
        return adminUserService.delete(id);
    }

}
